package com.company.project.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.exception.BusinessException;
import com.company.project.common.exception.code.BaseResponseCode;
import com.company.project.common.utils.Constant;
import com.company.project.common.utils.DataResult;
import com.company.project.common.utils.FileTypeUtil;
import com.company.project.entity.MatchProjectEntity;
import com.company.project.entity.MatchTeamEntity;
import com.company.project.entity.SysFilesEntity;
import com.company.project.entity.SysUser;
import com.company.project.entity.TeamUserEntity;
import com.company.project.service.HttpSessionService;
import com.company.project.service.MatchProjectService;
import com.company.project.service.MatchTeamService;
import com.company.project.service.SysFilesService;
import com.company.project.service.TeamUserService;
import com.company.project.service.UserService;
import com.company.project.vo.req.MatchTeamDTO;
import com.company.project.vo.resp.TeamInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 *
 * @author ls
 * @email *****@mail.com
 * @date 2021-02-02 20:34:19
 */
@RestController
@RequestMapping("/team")
@Api(tags = "前端比赛队伍管理")
public class TeamController extends BaseController{
	
	@Autowired
    private MatchTeamService matchTeamService;
    
    @Autowired
    private MatchProjectService matchProjectService;
    
    @Autowired
	private TeamUserService teamUserService;
    
    @Autowired
    private HttpSessionService httpSessionService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private SysFilesService sysFilesService;
    
    /*************************前端展示***********************************/
    
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "前端修改团队")
    @PostMapping("/update")
    @RequiresPermissions("team:add")
    @ResponseBody
    public DataResult updateTeam(@RequestBody MatchTeamDTO dto){
    	//比赛报名是否开启
    	if(getMatchStatus()) {
    		String userId = httpSessionService.getCurrentUserId();
    		SysUser user = userService.getById(userId);
    		if (null == user) {
    			throw new BusinessException(BaseResponseCode.TOKEN_ERROR);
    		}
    		TeamUserEntity teamUser = teamUserService
    				.getOne(Wrappers.<TeamUserEntity>lambdaQuery().eq(TeamUserEntity::getDcicUserId, user.getDcicUserId()));
    		if (teamUser != null) {//update
    			MatchTeamEntity entity = matchTeamService.getOne(
    					Wrappers.<MatchTeamEntity>lambdaQuery().eq(MatchTeamEntity::getTeamId, teamUser.getTeamId()));			
    			String oldUrl = entity.getPic();//保存旧照片路径		
    			BeanUtils.copyProperties(dto, entity);
    			if (!StringUtils.isEmpty(oldUrl) && !oldUrl.equals(dto.getPic())) {				
    				SysFilesEntity file = sysFilesService
    						.getOne(Wrappers.<SysFilesEntity>lambdaQuery().eq(SysFilesEntity::getUrl, entity.getPic()));
    				if(file!=null) {
    					String oldFileName = file.getUrl().substring(file.getUrl().lastIndexOf("/") + 1, file.getUrl().length());
    					String path = file.getUrl().substring(0,file.getUrl().lastIndexOf("/")+1);								
    					String newFileName = dto.getTeamName()+"-"+oldFileName;
    					sysFilesService.renameFile(file.getId(), newFileName);
    					entity.setPic(path+newFileName);
    					String fileType = oldFileName.substring(oldFileName.lastIndexOf(".") + 1, oldFileName.length()).toLowerCase();
    					newFileName = dto.getTeamName()+"."+fileType;
    					entity.setPicName(newFileName);								
    				}							
    			}
    			//删除旧文件
    			if(!StringUtils.isEmpty(oldUrl) && !oldUrl.equals(dto.getPic())) {
    				SysFilesEntity file = sysFilesService
    						.getOne(Wrappers.<SysFilesEntity>lambdaQuery().eq(SysFilesEntity::getUrl, oldUrl));
    				if(file != null) {
    					List<String> ids = new ArrayList<>();
    					ids.add(file.getId());
    					sysFilesService.removeByIdsAndFiles(ids);
    				}		
    			}	    	
    	        matchTeamService.updateById(entity);
    		}else {//add
    			//增加团队，先完善个人信息，否则不允许创建团队
    			if(StringUtils.isEmpty(user.getProvince())||
    					StringUtils.isEmpty(user.getCity())||
    					StringUtils.isEmpty(user.getSchool())||
    					StringUtils.isEmpty(user.getDegree())||
    					StringUtils.isEmpty(user.getMajor())||
    					/*StringUtils.isEmpty(user.getRemark())||*/
    					StringUtils.isEmpty(user.getOrganization())||
    					StringUtils.isEmpty(user.getPost())) {
    				throw new BusinessException(BaseResponseCode.UPDATE_PERSONAL_INFO_FIRST);
    			}			
    			MatchTeamEntity entity = new MatchTeamEntity();
    	    	BeanUtils.copyProperties(dto, entity);
    	    	//处理图片
    	    	if (!StringUtils.isEmpty(dto.getPic())) {				
    				SysFilesEntity file = sysFilesService
    						.getOne(Wrappers.<SysFilesEntity>lambdaQuery().eq(SysFilesEntity::getUrl, dto.getPic()));
    				if(file!=null) {
    					String oldFileName = file.getUrl().substring(file.getUrl().lastIndexOf("/") + 1, file.getUrl().length());
    					String path = file.getUrl().substring(0,file.getUrl().lastIndexOf("/")+1);					
    					String newFileName = dto.getTeamName()+"-"+oldFileName;
    					sysFilesService.renameFile(file.getId(), newFileName);
    					entity.setPic(path+newFileName);
    					String fileType = oldFileName.substring(oldFileName.lastIndexOf(".") + 1, oldFileName.length()).toLowerCase();
    					newFileName = dto.getTeamName()+"."+fileType;
    					entity.setPicName(newFileName);								
    				}							
    			}
    	    	
    	        matchTeamService.addMatchTeam(entity);
    	        //增加自己为队长
    	        TeamUserEntity tu = new TeamUserEntity();	        
    	        BeanUtils.copyProperties(user, tu);
    	        tu.setTeamId(entity.getTeamId());
    	        tu.setIsCaptain(Constant.IS_TRUE);			
    			teamUserService.addTeamUser(tu);
    		}  
            return DataResult.success();
    	}else {
			throw new BusinessException(BaseResponseCode.MATCH_STATUS_STOP);
		}
    	
    }
    
    @ApiOperation(value = "添加团队图片")
    @PostMapping("/upload")
    @RequiresPermissions("team:upload")
    public DataResult add(@RequestParam(value = "file") MultipartFile file) {
    	//比赛报名是否开启
    	if(getMatchStatus()) {
    		//判断文件是否空
            if (file == null || file.getOriginalFilename() == null || "".equalsIgnoreCase(file.getOriginalFilename().trim())) {
                return DataResult.fail("文件为空");
            }
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
            if(!FileTypeUtil.verifyFigFileType(fileType)) {
            	throw new BusinessException(BaseResponseCode.FILE_TYPE_ERROR);
            }
            return sysFilesService.saveFile(file,Constant.ATTACHMENT);
    	}else {
			throw new BusinessException(BaseResponseCode.MATCH_STATUS_STOP);
		}
    	
    }
    
    @ApiOperation(value = "前端查看团队信息")
    @PostMapping("/view")
    @RequiresPermissions("team:view")
    @ResponseBody
	public DataResult viewTeam() {
    	TeamInfo info = new TeamInfo();
		String userId = httpSessionService.getCurrentUserId();
		SysUser user = userService.getById(userId);
		if (null == user) {
			throw new BusinessException(BaseResponseCode.TOKEN_ERROR);
		}
		TeamUserEntity teamUser = teamUserService
				.getOne(Wrappers.<TeamUserEntity>lambdaQuery().eq(TeamUserEntity::getDcicUserId, user.getDcicUserId()));		 
		if (teamUser != null) {
			MatchTeamEntity entity = matchTeamService.getOne(
					Wrappers.<MatchTeamEntity>lambdaQuery().eq(MatchTeamEntity::getTeamId, teamUser.getTeamId()));
			BeanUtils.copyProperties(entity, info);
			// 获取所有队员
			List<TeamUserEntity> teamusers = teamUserService
					.list(Wrappers.<TeamUserEntity>lambdaQuery().eq(TeamUserEntity::getTeamId, teamUser.getTeamId()));
			info.setListUser(teamusers);
		}
		return DataResult.success(info);
	}
    
    @ApiOperation(value = "前端删除团队")
    @PostMapping("/delete")
    @RequiresPermissions("team:delete")
    @ResponseBody
	public DataResult deleteTeam() {   	
    	//比赛报名是否开启
    	if(getMatchStatus()) {
    		SysUser user = getCurrentUser();
    		TeamUserEntity teamUser = teamUserService
    				.getOne(Wrappers.<TeamUserEntity>lambdaQuery().eq(TeamUserEntity::getDcicUserId, user.getDcicUserId()));		 
    		if (teamUser != null && teamUser.getIsCaptain().equals(Constant.IS_TRUE)) {			
    			List<MatchProjectEntity> projects = matchProjectService
    					.list(Wrappers.<MatchProjectEntity>lambdaQuery().eq(MatchProjectEntity::getTeamId, teamUser.getTeamId()));
    			if (projects != null && projects.size() > 0) {
    				throw new BusinessException(BaseResponseCode.DELETE_PROJECT);
    			}
    			teamUserService.remove(Wrappers.<TeamUserEntity>lambdaQuery().eq(TeamUserEntity::getTeamId, teamUser.getTeamId()));
    			matchTeamService.removeById(teamUser.getTeamId());
    			return DataResult.success();
    		}else {
    			throw new BusinessException(BaseResponseCode.FORBIDDEN);
    		}
    	}else {
			throw new BusinessException(BaseResponseCode.MATCH_STATUS_STOP);
		}
    			
	}

}
